from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from typing import Dict
import sys
from datetime import datetime
import random
import os
from pathlib import Path

from websocket.ws_routes import handle_public_ws, handle_private_ws, ws_manager
from api.rest_routes import router as api_router
from config.settings import WS_HOST, WS_PORT, STATIC_DIR, TEMPLATE_DIR, BASE_DIR

app = FastAPI()

# 挂载静态文件
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")

# 模板引擎
templates = Jinja2Templates(directory=TEMPLATE_DIR)

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册API路由
app.include_router(api_router)

# WebSocket路由
app.add_api_websocket_route("/v2/ws/public", handle_public_ws)
app.add_api_websocket_route("/v2/ws/private", handle_private_ws)

# Web界面路由
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

# 模拟控制API
@app.post("/api/simulation/start")
async def start_simulation(time_range: Dict[str, int]):
    ws_manager.set_time_range(time_range["start_time"], time_range["end_time"])
    ws_manager.start_simulation()
    return {"status": "success"}

@app.post("/api/simulation/stop")
async def stop_simulation():
    ws_manager.stop_simulation()
    return {"status": "success"}

@app.get("/api/simulation/status")
async def get_status():
    return {
        "connected_clients": len(ws_manager.active_connections),
        "is_running": ws_manager.is_running
    }

# REST API 端点
@app.get("/api/v2/public/time")
async def get_server_time():
    return {
        "statusCode": "200",
        "data": int(datetime.now().timestamp() * 1000)
    }

@app.get("/api/v2/mix/market/ticker")
async def get_ticker(instId: str = "SETHSUSDT"):
    price = 2000 + random.uniform(-10, 10)
    return {
        "code": "0",
        "msg": "",
        "data": [{
            "instId": instId,
            "last": f"{price:.2f}",
            "lastSz": "0.01",
            "askPx": f"{price + 0.5:.2f}",
            "askSz": "1.0",
            "bidPx": f"{price - 0.5:.2f}",
            "bidSz": "1.0",
            "volume24h": "1000.0",
            "ts": str(int(datetime.now().timestamp() * 1000))
        }]
    }

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--gui":
        # GUI模式
        from gui_app import main
        main()
    else:
        # 命令行模式
        ssl_keyfile = os.path.join(BASE_DIR, "ssl", "server.key")
        ssl_certfile = os.path.join(BASE_DIR, "ssl", "server.crt")
        
        # 检查是否存在SSL证书
        if os.path.exists(ssl_keyfile) and os.path.exists(ssl_certfile):
            # SSL模式
            uvicorn.run(
                "main:app", 
                host=WS_HOST, 
                port=WS_PORT, 
                reload=True,
                ssl_keyfile=ssl_keyfile,
                ssl_certfile=ssl_certfile
            )
        else:
            # 非SSL模式
            uvicorn.run("main:app", host=WS_HOST, port=WS_PORT, reload=True)
